package com.ecarx.camera.ui;

import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.CallSuper;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * 所有 Fragment 的基类
 */
public abstract class BaseFragment extends Fragment {

    protected final String TAG = getClass().getSimpleName();

    protected View view;
    protected boolean isActive;
    private boolean hasResumed;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutResId(), container, false);
        initData();
        bindViews();
        initViews();
        return view;
    }

    /**
     * 获取 ContentView 的布局资源id
     *
     * @return ContentView 的布局资源 id
     */
    @LayoutRes
    protected abstract int getLayoutResId();

    /**
     * 初始化数据
     */
    @CallSuper
    protected void initData() {
    }

    /**
     * 绑定控件
     */
    @CallSuper
    protected void bindViews() {
    }

    /**
     * 初始化控件
     */
    @CallSuper
    protected void initViews() {
    }

    /**
     * @deprecated use {@link #onResume(boolean)} instead.
     */
    @Override
    @Deprecated
    public void onResume() {
        super.onResume();
        isActive = true;
        if (!hasResumed) {
            onResume(hasResumed = true);
        } else {
            onResume(false);
        }
    }

    /**
     * onResume回调的代理方法
     *
     * @param firstResume 是否第一次触发onResume回调
     */
    @CallSuper
    protected void onResume(boolean firstResume) {
    }

    @Override
    public void onPause() {
        super.onPause();
        isActive = false;
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initViews();
    }
}
